<template>
  <div class="inline">

    <span @click="openDrawer">
      <a v-if="type === 'link'">{{ action.text }}</a>
      <a-button v-else :type="action.config.color">{{ action.text }}</a-button>
    </span>

    <a-drawer
      v-model:visible="drawerVisible"
      :closable="false"
      :destroy-on-close="true"
      :title="action.config.title"
      placement="right"
      width="980px"
      @close="closeDrawer">
      <div>
        <page-filter ref="filter"
                     :config="action.config"
                     :extra-params="filterExtraParams"
                     @submit="handleFilterSubmit"/>

        <page-action ref="action"
                     :config="action.config"
                     :extra-params="actionExtraParams"
                     @change="handleActionChange"/>

        <page-table ref="table"
                    :config="action.config"
                    class="mt-2"/>
      </div>
    </a-drawer>
  </div>
</template>

<script setup>
const {action, type, selectedRows, extraParams} = defineProps(['action', 'type', 'selectedRows', 'extraParams']);

const table = ref(null);
const filter = ref(null);

const extraParamMapping = action.config.extraParamMapping;
const filterExtraParams = Object.keys(extraParamMapping.filter).reduce((prev, key) => {
  prev[extraParamMapping.filter[key]] = extraParams[key];
  return prev;
}, {});
const actionExtraParams = Object.keys(extraParamMapping.action).reduce((prev, key) => {
  prev[extraParamMapping.action[key]] = extraParams[key];
  return prev;
}, {});

const handleFilterSubmit = params => {
  table.value.loadData({
    params,
    page: 1
  });
}

const handleActionChange = () => {
  table.value.loadData();
}

const form = ref(null);
const drawerVisible = ref(false);
const closeDrawer = () => {
  drawerVisible.value = false;
}
const openDrawer = () => {
  drawerVisible.value = true;

  nextTick(() => {
    table.value.loadData({
      params: filter.value.getParams()
    });
  });
}
</script>
